<template>
  <div class="main-panel">
    <div class="main-header">
      <div class="header-btn">
        <el-button type="primary" icon="el-icon-plus" @click="openDiaolog(null)">添加</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="listData"
      row-key="id"
      :border="true"
      style="width: 100%">
      <el-table-column
        prop="name"
        label="角色名称"
        width="140">
      </el-table-column>
      <el-table-column
        prop="seq"
        label="排序"
        width="140"
        align="center">
      </el-table-column>
      <el-table-column
        prop="description"
        label="描述">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="140"
        align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status===0 ? '' : 'danger'">{{scope.row.status===0?'正常':'停用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="action"
        label="操作"
        width="300"
        align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="openResouceModel(scope.row.id)">授权</el-button>
          <el-button size="mini" @click="openDiaolog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="pageParams.page"
      :page-size="pageParams.rows"
      layout="total, prev, pager, next"
      :total="total">
    </el-pagination>

    <el-dialog
      :title="form.id?'修改':'添加'"
      :visible.sync="model"
      :draggable="true" width="500px">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="角色名称" required>
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.seq" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-tooltip :content="form.status===0?'正常':'禁用'" placement="right">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1">
            </el-switch>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="model = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">{{form.id?'修 改':'保 存'}}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="授权"
      :visible.sync="resourceModel"
      :draggable="true" width="500px">
      <el-tree
        class="filter-tree"
        show-checkbox
        :data="resourceTree"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        _filter-node-method="filterNode"
        ref="resourceTree">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resourceModel = false">取 消</el-button>
        <el-button type="primary" @click="handleResource">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, edit, add, del, findResourceIdListByRoleId, grant } from '_api/role'
import { allTrees } from '_api/resource'

export default {
  created () {
    this.loadData()
  },
  data () {
    return {
      listLoading: true,
      listData: [],
      pageParams: {
        page: 1,
        rows: 10,
        order: 'asc'
      },
      total: 0,
      model: false,
      form: {
      },
      resourceModel: false,
      resourceTree: [],
      selectedRoleId: 0,
      defaultProps: {
        children: 'children',
        label: 'text'
      }
    }
  },
  methods: {
    loadData () {
      this.listLoading = true
      getList(this.pageParams).then(res => {
        this.listData = res.rows
        this.total = res.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleSizeChange (val) {
      this.loadData()
    },
    handleCurrentChange (val) {
      this.loadData()
    },
    openDiaolog (row) {
      const self = this
      if (row) { self.form = row } else { self.form = {} }
      self.model = true
    },
    handleSubmit () {
      this.model = false
      if (!this.form.id) {
        add(this.form).then((res) => {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.loadData()
        })
      } else {
        edit(this.form).then(res => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.loadData()
        })
      }
    },
    openResouceModel (id) {
      this.selectedRoleId = id
      this.loadResouceTreeData()
    },
    deleteRole (id) {
      this.$confirm('您是否要删除当前角色!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.loadData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    loadResouceTreeData () {
      if (this.$refs.resourceTree) {
        this.$refs.resourceTree.setCheckedKeys([])
      }
      if (!this.resourceTree.length) {
        allTrees().then(res => {
          this.resourceTree = res
          this.resourceModel = true
          this.setChecked()
        })
      } else {
        this.resourceModel = true
        this.setChecked()
      }
    },
    setChecked () {
      findResourceIdListByRoleId({ id: this.selectedRoleId }).then(checkedKeys => {
        this.$refs.resourceTree.setCheckedKeys(checkedKeys)
      })
    },
    handleResource () {
      const resourceIds = this.$refs.resourceTree.getCheckedKeys()
      let formData = new FormData()
      formData.append('id', this.selectedRoleId)
      formData.append('resourceIds', resourceIds)
      grant(formData).then(res => {
        this.resourceModel = false
      })
    }
  }
}
</script>
